# -*- coding: utf-8 -*-
#只针对太一设备
import socket, time, random

class TelnetSock(object):
    def __init__(self, destip, username, password, dport = 23, sendInterval = 0.5, sourceIP = None, timeout=10):
        self.dest = (destip, dport)
        self.username = username
        self.password = password
        self.dutName = ''
        self.sendInterval = sendInterval
        self.timeout = timeout
        self.tsock = self.login(sourceIP)
    def login(self, sourceIP):
        if sourceIP:
            try:
                tsock = socket.create_connection(self.dest, timeout=self.timeout,
                                                 source_address=(sourceIP, random.randint(10000, 65535)))
            except:
                return
        else:
            tsock = socket.create_connection(self.dest)
        tsock.recv(1024)
        tsock.send('\xff\xfb\x01')
        tsock.recv(1024)
        tsock.send('\xff\xfb\x1f\xff\xfa\x1f\x00\x50\x00\x1d\xff\xf0\xff\xfd\x01\xff\xfd\x03')
        tsock.recv(1024)
        tsock.send(self.username + '\n')
        tsock.recv(1024)
        tsock.send(self.password + '\n')
        res = tsock.recv(1024)
        if res.find('password error')!=-1:
            tsock.close()
            print res
            return
        print res
        self.dutName = res[res.find('\r\n')+2:res.find('>')]
        return tsock
    def send_commands(self, commands):
        commandList = [l.strip() for l in commands.split('\n')]
        for c in commandList:
             self.tsock.send(c + '\n')
             recvData = ''
             while 1:
                 data = self.tsock.recv(1024)
                 recvData += data
                 if not data:
                     self.close()
                     break
                 elif data.find('--More--')!=-1:
                     self.tsock.send(' ')
                     continue
                 elif data.find(self.dutName)!=-1:
                     break
             print recvData,
             time.sleep(self.sendInterval)
    def run_with_user_input(self):
        if self.tsock:
            self.send_commands('enable')
        while self.tsock:
            try:
                userInput = raw_input('\r\n>>')
                if userInput == 'exit':
                    self.close()
                    return
            except KeyboardInterrupt:
                self.close()
                return
            self.send_commands(userInput)
    def close(self):
        self.tsock.close()


if __name__ == '__main__':
    destip = '192.168.10.106'
    username = 'admin'
    password = 'adc.admin'
    a = TelnetSock(destip, username, password, sourceIP = '192.168.10.102')
    a.close()